package order.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.*;
import order.client.CarrierClient;
import order.mapper.OperationRecordMapper;
import order.mapper.ShippingOrderMapper;
import order.mapper.TruckOrderMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TruckOrderService {
    @Resource
    ShippingOrderMapper shippingOrderMapper;
    @Resource
    OperationRecordMapper operationRecordMapper;
    @Resource
    TruckOrderMapper truckOrderMapper;
    @Resource
    CarrierClient carrierClient;

    public List<TruckOrder> getTruckOrder(Long id) {
        QueryWrapper wrapper = new QueryWrapper();
        if(id!=null) wrapper.like("driver_id", id);
        List<TruckOrder> truckOrderList =truckOrderMapper.selectList(wrapper);
        truckOrderList.forEach(t -> {
            ShippingOrder s = shippingOrderMapper.selectById(t.getOrderId());
            t.setShippingOrder(s);
            List<OperationRecord> rl = operationRecordMapper.selectList(new QueryWrapper<OperationRecord>().eq("type",2).eq("order_id",t.getId()));
            t.setOperationRecords(rl);
        });
        return truckOrderList;
    }

    public String changeState(Integer state, Long id, Long operator, String location, String unexpectedInfo, Double unexpectedPrice) {
        TruckOrder t = truckOrderMapper.selectById(id);
        String res = null;
        OperationRecord task = new OperationRecord(2,id,state,operator,new Date());
        switch (state) {
            case 3:
                t.setState(4);
                res = "已揽收";
                break;
            case 4:
                t.setState(5);
                res = "已发车";
                break;
            case 5:
                t.setLocation(location);
                task.setLocation(location);
                res = "到达新站点上报完成";
                break;
            case 6:
                t.setState(6);
//                //更新货车和司机状态
//                Truck truck = carrierClient.selectTruckById(t.getTruckId());
//                truck.setState(0);
//                carrierClient.updateTruckById(truck);
//                carrierClient.updateDriverState(0, t.getCarrierId(),t.getDriverId());
                res = "到达";
                break;
            case 7:
                task.setUnexpectedInfo(unexpectedInfo);
                task.setUnexpectedPrice(unexpectedPrice);
                t.setUnexpectedCost(t.getUnexpectedCost()+unexpectedPrice);
                res = "上报意外情况";

        }
        truckOrderMapper.updateById(t);
        operationRecordMapper.insert(task);
        return res;
    }

}
